package org.example.myweibo.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.example.myweibo.common.result.JsonResult;
import org.example.myweibo.common.result.StatusCode;
import org.example.myweibo.mapper.UserMapper;
import org.example.myweibo.pojo.dto.UserRegDTO;
import org.example.myweibo.pojo.entity.User;
import org.example.myweibo.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Api(tags = "用户模块")
@RestController
@RequestMapping("/v1/users")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @ApiOperation("用户注册功能")
    @PostMapping("/reg")
    public JsonResult register(@RequestBody UserRegDTO userRegDTO){
        String username = userRegDTO.getUsername();
        User findUser = userMapper.selectByUsername(username);
        if(findUser != null){
            return new JsonResult(StatusCode.USERNAME_EXISTS);
        }

        User user = new User();
        BeanUtils.copyProperties(userRegDTO, user);
        user.setCreated(new Date());
        userMapper.insert(user);
        return JsonResult.success();
    }


    @ApiOperation("用户登录功能")
    @PostMapping("/login")
    public JsonResult login(@RequestBody @Validated UserRegDTO userRegDTO, @ApiIgnore HttpSession session) {
        User user = userMapper.selectByUsername(userRegDTO.getUsername());
        if (user != null) {
            if (user.getPassword().equals(userRegDTO.getPassword())) {
                session.setAttribute("user", user);
                return JsonResult.success();
            }else {
                return new JsonResult(StatusCode.PASSWORD_ERROR);
            }
        }else {
            return new JsonResult(StatusCode.USERNAME_ERROR);
        }
    }

    @ApiOperation("获取当前登录用户信息功能")
    @GetMapping("/currentUser")
    public JsonResult currentUser(@ApiIgnore HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return new JsonResult(StatusCode.NOT_LOGIN);
        }else {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            return JsonResult.success(userVO);
        }
    }

    @ApiOperation("用户退出登录功能")
    @GetMapping("/logout")
    public void logout(@ApiIgnore HttpSession session) {
        session.removeAttribute("user");
    }
}
